package com.pmt.feedplayer.ui

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.pmt.feedplayer.core.PlayerManager
import com.pmt.feedplayer.data.PlaybackState
import com.pmt.feedplayer.data.PlaybackProgress
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import java.io.File

/**
 * 音频播放器ViewModel
 */
class AudioPlayerViewModel : ViewModel() {
    // 播放状态
    val showPlayer = MutableLiveData(false)
    val hideBottomNavBar = MutableLiveData(false)
    val isPlaying = MutableLiveData(false)
    val currentAudioFile = MutableLiveData<File?>(null)
    val currentPosition = MutableLiveData(0L)
    val duration = MutableLiveData(0L)
    
    // 使用PlayerManager来管理音频播放
    private val playerManager: PlayerManager = PlayerManager.getInstance()
    
    init {
        // 监听播放状态变化
        viewModelScope.launch {
            if (playerManager.playbackStateFlow != null) {
                playerManager.playbackStateFlow!!.collect { 
                    when (it) {
                        PlaybackState.PLAYING -> isPlaying.value = true
                        PlaybackState.PAUSED, PlaybackState.IDLE -> 
                            isPlaying.value = false
                        PlaybackState.ERROR -> {
                            isPlaying.value = false
                            Log.e("AudioPlayerViewModel", "播放错误")
                        }
                        else -> {}
                    }
                }
            }
        }
        
        // 监听进度变化
        viewModelScope.launch {
            if (playerManager.progressFlow != null) {
                playerManager.progressFlow!!.collect { 
                    if (it is PlaybackProgress) {
                        currentPosition.value = it.currentPosition
                        duration.value = it.duration
                    }
                }
            }
        }
        
        // 监听错误
        viewModelScope.launch {
            if (playerManager.errorFlow != null) {
                playerManager.errorFlow!!.collect { 
                    if (it is Throwable) {
                        Log.e("AudioPlayerViewModel", "播放错误", it)
                    } else {
                        Log.e("AudioPlayerViewModel", "播放错误: $it")
                    }
                    isPlaying.value = false
                }
            }
        }
    }

    /**
     * 加载音频文件
     */
    fun loadAudio(audioFile: File) {
        try {
            // 加载音频文件
            playerManager.loadVideo(audioFile.absolutePath)
            
            // 更新状态
            currentAudioFile.value = audioFile
            showPlayer.value = true
            hideBottomNavBar.value = true
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "加载音频失败", e)
        }
    }
    
    /**
     * 播放音频（无参数版本）
     */
    fun playAudio() {
        try {
            // 延迟一点时间开始播放，确保播放器准备就绪
            viewModelScope.launch {
                kotlinx.coroutines.delay(100)
                playerManager.play()
            }
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "播放音频失败", e)
            isPlaying.value = false
        }
    }
    
    /**
     * 播放音频（带文件参数版本）
     */
    fun playAudio(audioFile: File) {
        try {
            loadAudio(audioFile)
            playAudio()
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "播放音频失败", e)
            isPlaying.value = false
        }
    }

    /**
     * 暂停/播放切换
     */
    fun togglePlayPause() {
        try {
            if (isPlaying.value == true) {
                pause()
            } else {
                playerManager.play()
            }
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "切换播放状态失败", e)
        }
    }

    /**
     * 暂停播放
     */
    fun pause() {
        try {
            playerManager.pause()
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "暂停播放失败", e)
        }
    }
    
    /**
     * 暂停播放（另一个名称的方法，用于UI调用）
     */
    fun pauseAudio() {
        pause()
    }
    
    /**
     * 快进
     */
    fun fastForward(milliseconds: Int) {
        try {
            val newPosition = (currentPosition.value ?: 0L) + milliseconds
            playerManager.seekTo(newPosition)
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "快进失败", e)
        }
    }

    /**
     * 快退
     */
    fun rewind(milliseconds: Int) {
        try {
            val newPosition = maxOf(0, (currentPosition.value ?: 0L) - milliseconds)
            playerManager.seekTo(newPosition)
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "快退失败", e)
        }
    }
    
    /**
     * 跳转到指定位置（Long参数版本）
     */
    fun seekTo(position: Long) {
        try {
            playerManager.seekTo(position)
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "跳转失败", e)
        }
    }
    
    /**
     * 跳转到指定位置（Int参数版本）
     */
    fun seekTo(position: Int) {
        seekTo(position.toLong())
    }

    /**
     * 关闭播放器
     */
    fun closePlayer() {
        pause()
        showPlayer.value = false
        hideBottomNavBar.value = false
    }
    
    /**
     * ViewModel销毁时释放资源
     */
    override fun onCleared() {
        super.onCleared()
        try {
            playerManager.release()
        } catch (e: Exception) {
            Log.e("AudioPlayerViewModel", "释放资源失败", e)
        }
    }
}